package com.oocl.o2o.client.dao.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.stereotype.Repository;
import com.oocl.o2o.client.dao.CommentaryDao;
import com.oocl.o2o.client.entity.Commentary;

/**
 * 
 * @author HEHA4
 *
 */

@Repository(value="commentaryDaoImpl")
public class CommentaryDaoImpl implements CommentaryDao {

	@PersistenceContext(name="un")
	private EntityManager manager;
	
	@Override
	public Commentary add(Commentary commentary) {
		manager.persist(commentary);
		return commentary;
	}

	@Override
	public List<Commentary> findCommentaryByCustomerId(String customerId) {
		String jpql = "select c from Commentary c where c.customer.id =:customerId";
		List<Commentary> commentaries =manager.createQuery(jpql)
				.setParameter("customerId", customerId)
				.getResultList();
		
		return commentaries; 
	}

	/**
	 * find by merchantId
	 */
	@Override
	public List<Commentary> findCommentaryByMerchantName(String merchantName) {
		String jpql = "select c from Commentary c where c.merchant.username =:merchantName";
		List<Commentary> commentaries =manager.createQuery(jpql)
				.setParameter("merchantName", merchantName)
				.getResultList();
		
		return commentaries; 
	}

	@Override
	public Commentary update(Commentary commentary) {
		Commentary c = manager.find(Commentary.class, commentary.getId());
		//先将本来的变成游离态
		manager.clear();
		manager.merge(commentary);
		//进行游离态-->managed状态
		return commentary;
	}

	@Override
	public Commentary findById(String id) {
		String jpql = "select c from Commentary c where c.id =:id";
		List<Commentary> commentaries =manager.createQuery(jpql)
				.setParameter("id", id)
				.getResultList();
		if(commentaries.isEmpty()){
			return null;
		}
		else {
			return commentaries.get(0);
		} 
	}

}
